<template>
	<view>
		<uni-forms>
			<uni-row>
				<uni-col :span="15">
					<uni-forms-item label="服务单号">
						<uni-easyinput :styles="inputStyles" :disabled="true" v-model="orderSn"
							type="text"></uni-easyinput>
					</uni-forms-item>
				</uni-col>
				<uni-col :span="9">
					<uni-forms-item label="派单人">
						<uni-easyinput :styles="inputStyles" :disabled="true" v-model="username"></uni-easyinput>
					</uni-forms-item>
				</uni-col>
			</uni-row>
			<uni-forms-item label="服务类型">
				<uni-row>
					<uni-col :span="16">
						<uni-easyinput :styles="inputStyles" type="text" :disabled="true" v-model="serviceName" />
					</uni-col>
					<uni-col :span="8">
						<button v-if="formData.customer_location" type="primary" size="mini"
							@click="openNavigation(formData.customer_location.latitude,formData.customer_location.longitude,formData.customer_location.name)"
							icon="map" shape="circle">车辆位置</button>
						<button type="success" size="mini" @click="makeCall(formData.customer_phone)" icon="phone"
							shape="circle">联系客户</button>
					</uni-col>
				</uni-row>
			</uni-forms-item>


			<uni-forms-item label="客户需求">
				<uni-easyinput :styles="inputStyles" type="textarea" :disabled="true" :autoHeight="true"
					v-model="formData.customer_needs" trim="both"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item label="备注">
				<uni-row>
					<uni-col :span="18">
						<uni-easyinput :styles="inputStyles" type="text" :disabled="true"
							v-model="formData.service_content"></uni-easyinput>
					</uni-col>
					<uni-col v-if="updated" :span="6">
						<uni-fav :checked="checkedContent" :circle="true" :content-text="checkedContentText"
							:star="false" bgColor="#ff0000" bgColorChecked="#eeeeee" fgColor="#FFFFFF"
							fgColorChecked="#666666" @click="serviceContentCheck" />
					</uni-col>
				</uni-row>
			</uni-forms-item>
			<uni-forms-item v-if="checkedContent" label="补充备注">
				<uni-easyinput ref="addContentInput" :styles="inputStyles" type="textarea" @blur="serviceContentSave"
					:disabled="!updated" :autoHeight="true" v-model="formData.service_add_content"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item v-if="checkedContent" label="增派协助">
				<uni-data-picker v-model="formData.help_butler_id" popup-title="增派车管家协助" :localdata="butlerList"
					:disabled="!updated" @change="selectHelpButler" placeholder="点击选择车管家"></uni-data-picker>
			</uni-forms-item>

			<uni-forms-item v-if="role!='butler'" label="车管家">
				<uni-data-picker v-model="formData.butler_id" :disabled="true" :localdata="butlerList"
					placeholder="选择车管家"></uni-data-picker>
			</uni-forms-item>

			<uni-forms-item label="联盟门店">
				<uni-row>
					<uni-col :span="16">
						<uni-easyinput :styles="inputStyles" type="text" :disabled="true" v-model="storeName" />
					</uni-col>
					<uni-col :span="8">
						<button v-if="formData.store_id[0]?.location" type="primary" size="mini" @click="openNavigation(formData.store_id[0].location.coordinates[0],
			                formData.store_id[0].location.coordinates[1],'')" icon="map" shape="circle">查看位置</button>
					</uni-col>
				</uni-row>
			</uni-forms-item>
			<uni-forms-item label="协议价">
				<uni-easyinput :styles="inputStyles" type="number" :disabled="true"
					v-model="formData.price"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item v-if="role==='officer'" label="收款金额">
				<uni-easyinput :styles="inputStyles" type="digit" :disabled="formData.status != 4"
					v-model.number="formData.payment_price"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item v-if="role==='officer'" label="交易单号">
				<uni-easyinput :styles="inputStyles" type="text" :disabled="formData.status != 4"
					v-model="formData.payment_order_id"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item label="预计收益">
				<uni-easyinput :styles="inputStyles" type="number" :disabled="true"
					v-model="formData.butler_income"></uni-easyinput>
			</uni-forms-item>
		</uni-forms>
		<view class="forms-row">
			<text class="forms-col">客户资料(行驶证正副本/身份证正反面等)</text>
		</view>
		<view class="uni-flex uni-row forms-row">
			<view class="flex-item forms-col">
				<uni-file-picker v-model="formData.license_photos_main.car_license_face" :image-styles="imageStyles"
					:disabled="!updated" :del-icon="updated" :sizeType="['compressed']" return-type="object"
					@success="onCarLicenseSuccess($event, 'face')" @delete="onLicenseDelete">行驶证正本</uni-file-picker>
			</view>
			<view class="flex-item forms-col">
				<uni-file-picker v-model="formData.license_photos_main.car_license_back" :image-styles="imageStyles"
					:disabled="!updated" :del-icon="updated" :sizeType="['compressed']" return-type="object"
					@success="onCarLicenseSuccess($event, 'back')" @delete="onLicenseDelete">行驶证副本</uni-file-picker>
			</view>
			<view class="flex-item forms-col">
				<uni-file-picker v-model="formData.license_photos_main.idcard_face" :image-styles="imageStyles"
					:disabled="!updated" :del-icon="updated" :sizeType="['compressed']" return-type="object"
					@success="onLicenseSuccess" @delete="onLicenseDelete">身份证正面</uni-file-picker>
			</view>
			<view class="flex-item forms-col">
				<uni-file-picker v-model="formData.license_photos_main.idcard_back" :image-styles="imageStyles"
					:disabled="!updated" :del-icon="updated" :sizeType="['compressed']" return-type="object"
					@success="onLicenseSuccess" @delete="onLicenseDelete">身份证反面</uni-file-picker>
			</view>
			<view class="flex-item forms-col">
				<uni-file-picker v-model="formData.license_photos_main.other" :image-styles="imageStyles"
					:disabled="!updated" :del-icon="updated" :sizeType="['compressed']" return-type="object"
					@success="onLicenseSuccess" @delete="onLicenseDelete">检车记录</uni-file-picker>
			</view>
		</view>
		<view class="forms-row">
			<text class="forms-col">工单节点照片</text>
		</view>
		<view v-for="(item, index) in formData.service_photos" :key="item.url" class="uni-flex uni-row forms-row">
			<view class="flex-item forms-col">
				<uni-file-picker v-model="formData.service_photos[index]" :image-styles="imageStyles"
					:disabled="!updated" :del-icon="updated" :sizeType="['compressed']" :sourceType="['camera']"
					return-type="object" @success="saveServicePhoto" @delete="onServiceDelete">拍照</uni-file-picker>
			</view>
			<uni-easyinput class="forms-textarea" v-model="formData.service_photos[index].desc" placeholder="点击填写描述"
				:disabled="!updated" type="textarea" min-height="60" auto-height :clearable="true" :styles="inputStyles"
				@change="saveServicePhoto"></uni-easyinput>
		</view>
		<view v-if="updated" class="uni-flex uni-row forms-row">
			<view class="flex-item forms-col">
				<uni-file-picker ref="serviceFilePicker" :image-styles="imageStyles" :disabled="!updated"
					:sizeType="['compressed']" :sourceType="['camera']" return-type="object"
					@success="onServiceUploaded">拍照</uni-file-picker>
			</view>
			<view class="flex-item forms-col">
				<button type="warn" class="uni-button" :disabled="!updated" @click="doneServiceValidate">拍摄完成通知客户</button>
			</view>
		</view>

		<uni-popup ref="popup" type="center">
			<image :src="qrCodeUrl" mode="widthFix"></image>
		</uni-popup>
		<view v-if="role==='officer'" class="uni-button-group">
			<button type="primary" class="uni-button" @click="officerAudit"
				:disabled="formData.status!=4">财务审核完成</button>
		</view>
		<view v-if="(role==='butler' || (role==='supervisor' && formData.score === 1)) && formData.status>=2"
			class="uni-button-group">
			<button type="primary" :disabled="paused" class="uni-button" @click="open">收款二维码</button>
			<button type="warn" :disabled="(formData.status!=3 && formData.status!=2) || paused" class="uni-button"
				@click="doneCharge">收款完成,通知核算</button>
		</view>
		<view v-if="role==='supervisor'" class="uni-button-group">
			<button type="primary" class="uni-button" @click="score(5)" :disabled="formData.score>=1">优秀方案</button>
			<button type="warn" class="uni-button" @click="score(1)" :disabled="formData.score>=1">介入协助</button>
			<button type="primary" class="uni-button" open-type="share">录数据库</button>
		</view>
	</view>
</template>

<script>
	const userInfo = uniCloud.getCurrentUserInfo()
	const db = uniCloud.database();
	const dbCollectionName = 'yycw_car_service_order';
	export default {
		data() {
			let formData = {
				"customer_needs": "",
				"customer_phone": "",
				"service_content": "",
				"price": 0,
				"butler_income": 0,
				"butler_id": '',
				"help_butler_id": '',
				"license_photos_main": {
					car_license_face: {},
					car_license_back: {},
					idcard_face: {},
					idcard_back: {},
					other: {}
				},
				"archives_id": "",
				"license_photos": [],
				"service_photos": [],
				"type_id": [],
				"store_id": [],
				"status": 2,
				"score": 0,
				"case": 0,
				"payment_status": 0,
				"payment_price": 0,
				"payment_order_id": "",
				"customer_location": {}
			}
			return {
				formData,
				orderSn: '',
				username: '',
				role: 'user',
				updated: false,
				butlerList: [],
				inputStyles: {
					color: '#000000',
					disableColor: '#ffffff'
				},
				checkedContent: false,
				checkedContentText: {
					contentDefault: '补充',
					contentFav: '取消'
				},
				tempIds: {
					butler: ['T_GL6442fynSz-3nGOZlsaAWzxCrrVyJ4BIBKNRvXQo',
						'H8eA0MIzOkqWsiiFWDsDWTQZlCkntzUvdB6XDYmzJ-c',
						'JUBkII7UkA83l6PrrhUQ8iOp4iXZMPugMtjuP7jl43w'
					],
					officer: ['JYrmMPR6Fs8KdyFb4Y2t5gc2Tq88Qm3dGvn4qmS2w70']
				},
				serviceName: '',
				storeName: '',
				qrCodeUrl: 'https://mp-6fb2680d-8625-4497-8e9b-9e026f99b673.cdn.bspapp.com/butlerqrcode/yanglingfengqrcode.jpg',
				showPopup: false,
				imageStyles: {
					width: 72,
					height: 72,
					border: {
						color: "#ff5a5f",
						width: 2,
						style: 'none',
						radius: '2px'
					}
				},
				paused: false,
				imgWhiteList: ['jpg', 'png', 'webp', 'jpeg', 'bmp', 'heic', 'heif']
			}
		},
		onLoad(options) {
			if (!options.id) {
				uni.showToast({
					icon: 'none',
					title: '请先选择服务订单'
				})
				setTimeout(() => this.autoNavigateBack(), 500)
				return
			}
			this.formDataId = options.id
			if (options.role) {
				if (!this.uniIDHasRole(options.role)) {
					uni.showToast({
						icon: 'none',
						title: '无权限访问'
					})
					setTimeout(() => this.autoNavigateBack(), 500)
					return
				}
				this.role = options.role
			}
			this.getDetail(this.formDataId)
			if (options.role != 'user') {
				this.getDatas()
			}
		},
		async onShareAppMessage(from, target) {
			if ('button' === from && !this.formData.case) {
				uni.showLoading({
					title: '保存中',
					mask: true
				})
				const value = {
					"case": 1
				}

				await db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					this.formData.case = 1
					uni.showToast({
						icon: 'success',
						title: '操作成功'
					})

				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
				return {
					title: '录数据库:' + this.serviceName || '',
					path: '/pages/yycw_car_service_order/service?id=' + this.formDataId
				}
			}
			return {
				title: '服务工单:' + this.serviceName || '',
				path: '/pages/yycw_car_service_order/detail?id=' + this.formDataId
			}
		},
		methods: {
			uniIDHasRole(role) {
				return (userInfo['role'] || []).includes(role)
			},
			autoNavigateBack() {
				const pages = getCurrentPages()
				console.debug('autoNavigateBack length:' + pages.length)
				if (pages.length > 1) {
					uni.navigateBack({
						delta: 1
					})
				} else {
					uni.redirectTo({
						url: '/pages/index/index'
					}) // 或使用reLaunch/switchTab
				}
			},
			async onServiceUploaded(e) {
				const newItem = e.tempFiles[0]
				// console.debug(JSON.stringify(newItem))
				// console.debug(JSON.stringify(this.formData.service_photos))
				this.formData.service_photos.push(newItem)
				this.$refs.serviceFilePicker.clearFiles()
				await this.saveServicePhoto()
			},
			async selectHelpButler() {
				uni.showLoading({
					title: '增派中',
					mask: true
				})
				db.collection(dbCollectionName).doc(this.formDataId).update({
					help_butler_id: this.formData.help_butler_id
				}).then((res) => {
					this.formData.service_add_content = ''
					uni.showToast({
						icon: 'success',
						title: '完成增派协助'
					})
				}).catch((err) => {
					// console.debug(JSON.stringify(err))
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			async getDatas() {
				try {
					// 获取车管家列表
					const butlerRes = await db.collection('uni-id-users')
						.where({
							role: 'butler',
							status: 0
						})
						.field('nickname as text, _id as value')
						.get()

					this.butlerList = butlerRes.result.data
				} catch (e) {
					console.error('获取数据失败:', e)
					uni.showToast({
						icon: 'error',
						title: '获取数据失败'
					})
				}
			},
			serviceContentCheck() {
				this.checkedContent = !this.checkedContent
				if (this.checkedContent) {
					if (this.$refs.addContentInput) {
						this.$nextTick(() => {
							this.$refs.addContentInput.focus()
						})
					}
				} else if (this.formData.service_add_content || this.formData.help_butler_id) {
					uni.showLoading({
						title: '重置中'
					})
					db.collection(dbCollectionName).doc(this.formDataId).update({
						service_add_content: '',
						help_butler_id: ''
					}).then((res) => {
						this.formData.service_add_content = ''
						this.formData.help_butler_id = ''
						uni.showToast({
							icon: 'success',
							title: '已重置补充备注'
						})
					}).catch((err) => {
						// console.debug(JSON.stringify(err))
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						uni.hideLoading()
					})
				}
			},
			serviceContentSave() {
				if (!this.formData.service_add_content) {
					if (this.$refs.addContentInput) {
						this.$nextTick(() => {
							this.$refs.addContentInput.focus()
						})
					}
				} else {
					uni.showLoading({
						title: '保存中'
					})
					db.collection(dbCollectionName).doc(this.formDataId).update({
						service_add_content: this.formData.service_add_content
					}).then((res) => {
						uni.showToast({
							icon: 'success',
							title: '已保存'
						})
					}).catch((err) => {
						// console.debug(JSON.stringify(err))
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						uni.hideLoading()
					})
				}
			},
			officerAudit() {
				uni.requestSubscribeMessage({
					tmplIds: this.tempIds.officer, // 改成你的小程序订阅消息模板id
					success: (res) => {},
					fail: (res) => {
						uni.showToast({
							title: JSON.stringify(res.errMsg),
							icon: 'error',
							duration: 1000
						});
						if (20001 === res.errCode) {
							console.debug('sub fail no temp return')
						}

					},
				})
				if (this.formData.payment_price <= 0) {
					uni.showToast({
						icon: 'none',
						title: '请填写实际收款金额'
					})
					return
				}
				if (!this.formData.payment_order_id) {
					uni.showToast({
						icon: 'none',
						title: '请填写农行交易单号'
					})
					return
				}
				uni.showLoading({
					title: '保存中'
				})
				// console.debug(this.formData.payment_price)
				const value = {
					payment_price: this.formData.payment_price,
					payment_order_id: this.formData.payment_order_id,
					officer_id: userInfo.uid,
					payment_status: 2,
					status: 5,
					dates: {
						financial_audit: new Date()
					}
				}
				db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					this.formData.status = 5
					uni.showToast({
						icon: 'success',
						title: '核算完成',
						complete() {
							this.autoNavigateBack()
						}
					})
				}).catch((err) => {
					// console.debug(JSON.stringify(err))
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			collectCase() {
				if (this.formData.case > 0) {
					uni.showToast({
						icon: 'none',
						title: '本工单已收集操作方案，不可重复操作'
					})
					return
				}
				uni.showLoading({
					title: '保存中'
				})
				const value = {
					"case": 1
				}

				db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					this.formData.case = 1
					uni.showToast({
						icon: 'success',
						title: '操作成功'
					})

				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			score(s) {
				if (!s || s <= 0) {
					return
				}
				if (this.formData.score > 0) {
					uni.showToast({
						icon: 'none',
						title: '本工单已评优或介入，不可重复操作'
					})
					return
				}
				uni.showLoading({
					title: '保存中'
				})
				const value = {
					"score": s,
					"dates": {
						"score_date": new Date()
					},
					"supervisor_id": userInfo.uid
				}
				db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					this.formData.score = s
					uni.showToast({
						icon: 'success',
						title: '操作成功'
					})

				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			open() {
				this.$refs.popup.open()
			},
			async update(value) {
				console.debug('update value:' + JSON.stringify(value))
				uni.showLoading({
					title: '保存中···',
					mask: true
				})
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			async onCarLicenseSuccess(e, type) {
				let action = 'recognizeVehicleLicenseByOrder',
					params = {
						url: e.tempFiles[0].url,
						name: e.tempFiles[0].name,
						extname: e.tempFiles[0].extname
					}
				if (this.formData.archives_id &&
					((this.formData.license_photos_main.car_license_face && type === 'back') ||
						(this.formData.license_photos_main.car_license_back && type === 'face'))) { //已有档案id并且
					action = 'recognizeVehicleLicenseToComplete'
					params.type = type
					params.archivesId = this.formData.archives_id
				} else {
					params.butlerId = this.formData.butler_id
					params.orderId = this.formDataId
				}
				uni.showLoading({
					title: '识别中···',
					mask: true
				})
				await uniCloud.callFunction({
						name: 'yycw-car-archives',
						data: {
							"action": action,
							"params": params,
						}
					})
					.then(res => {
						console.debug(JSON.stringify(res))
						uni.hideLoading()
						if (!res.result.success) {
							if (type === 'face') {
								this.formData.license_photos_main.car_license_face = null
							} else {
								this.formData.license_photos_main.car_license_back = null
							}
							uni.showToast({
								title: res.result.message,
								icon: 'error'
							})
							return
						}
						//判断是否需要保存绑定档案
						const data = res.result.data
						if (!this.formData.archives_id) {
							if (!data.id) {
								console.error('缺少汽车档案标识')
								return
							}
							db.collection(dbCollectionName).doc(this.formDataId).update({
								"archives_id": data.id
							}).then(res => {
								this.formData.archives_id = data.id
							})
						}
						//是否需要修正图片
						if (data?.back && type === 'face') {
							console.debug('修正为正本')
							this.formData.license_photos_main.car_license_back = this.formData.license_photos_main
								.car_license_face
							this.formData.license_photos_main.car_license_face = {}
						} else if (data?.face && type === 'back') {
							console.debug('修正为副本')
							this.formData.license_photos_main.car_license_face = this.formData.license_photos_main
								.car_license_back
							this.formData.license_photos_main.car_license_back = {}
						}

						this.onLicenseSuccess()
					})
			},
			async onLicenseSuccess(e) {

				// const value = {
				// 	"license_photos_main": {
				// 		"car_license_face": this.formData.license_photos_main.car_license_face?{ "url":this.formData.license_photos_main.car_license_face.url, "extname":this.formData.license_photos_main.car_license_face.extname, "name":this.formData.license_photos_main.car_license_face.name }:null,
				// 		"car_license_back": this.formData.license_photos_main.car_license_back?{ "url":this.formData.license_photos_main.car_license_back.url, "extname":this.formData.license_photos_main.car_license_back.extname, "name":this.formData.license_photos_main.car_license_back.name }:null,
				// 		"idcard_face": this.formData.license_photos_main.idcard_face?{ "url":this.formData.license_photos_main.idcard_face.url, "extname":this.formData.license_photos_main.idcard_face.extname, "name":this.formData.license_photos_main.idcard_face.name }:null,
				// 		"idcard_back": this.formData.license_photos_main.idcard_back?{ "url":this.formData.license_photos_main.idcard_back.url, "extname":this.formData.license_photos_main.idcard_back.extname, "name":this.formData.license_photos_main.idcard_back.name }:null,
				// 		"other": this.formData.license_photos_main.other?{ "url":this.formData.license_photos_main.other.url, "extname":this.formData.license_photos_main.other.extname, "name":this.formData.license_photos_main.other.name }:null,
				// 	}
				// }

				const value = {
					license_photos_main: Object.fromEntries(
						['car_license_face', 'car_license_back', 'idcard_face', 'idcard_back', 'other']
						.map(key =>
							this.formData.license_photos_main?.[key] ? [key, {
								url: this.formData.license_photos_main[key].url,
								extname: this.formData.license_photos_main[key].extname,
								name: this.formData.license_photos_main[key].name
							}] :
							undefined
						)
						.filter(Boolean) // 自动过滤掉 undefined
					)
				}
				console.debug('license_photos_main:' + JSON.stringify(this.formData.license_photos_main))
				this.update(value)
			},
			// onLicenseSuccess2(e) {
			// 	const newPhotos = this.formData.license_photos.map(file => {
			// 		return {
			// 			url: file.url,
			// 			extname: file.extname,
			// 			name: file.name
			// 		}
			// 	})
			// 	// console.debug('license_photos' + JSON.stringify(this.formData.license_photos))
			// 	return db.collection(dbCollectionName).doc(this.formDataId).update({
			// 		license_photos: newPhotos
			// 	}).then((res) => {
			// 		this.formData.status = 2
			// 		uni.showToast({
			// 			icon: 'success',
			// 			title: '上传成功'
			// 		})

			// 	}).catch((err) => {
			// 		uni.showModal({
			// 			content: err.message || '请求服务失败',
			// 			showCancel: false
			// 		})
			// 	})
			// },
			onLicenseDelete(e) {
				const delPhoto = e.tempFile
				this.formData.license_photos = this.formData.license_photos.filter(oldPhoto => {
					return delPhoto.url != oldPhoto.url
				})
				const newPhotos = this.formData.license_photos.map(file => {
					return {
						url: file.url,
						extname: file.extname,
						name: file.name
					}
				})
				return db.collection(dbCollectionName).doc(this.formDataId).update({
					license_photos: newPhotos
				}).then((res) => {
					uni.showToast({
						icon: 'success',
						title: '删除成功'
					})
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			async saveServicePhoto() {
				uni.showLoading({
					title: '保存中...',
					mask: true
				})
				const newPhotos = this.formData.service_photos.map(file => {
					return {
						url: file.url,
						extname: file.extname,
						name: file.name,
						desc: file.desc
					}
				})
				// console.debug(JSON.stringify(newPhotos))
				await db.collection(dbCollectionName).doc(this.formDataId).update({
					service_photos: newPhotos
				}).then((res) => {
					uni.showToast({
						icon: 'success',
						title: '保存成功'
					})
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			onServiceDelete(e) {
				const delPhoto = e.tempFile
				// console.debug(JSON.stringify(e))
				this.formData.service_photos = this.formData.service_photos.filter(oldPhoto => {
					return delPhoto.url != oldPhoto.url
				})
				const newPhotos = this.formData.service_photos.map(file => {
					return {
						url: file.url,
						extname: file.extname,
						name: file.name,
						desc: file.desc
					}
				})
				return db.collection(dbCollectionName).doc(this.formDataId).update({
					service_photos: newPhotos
				}).then((res) => {
					uni.showToast({
						icon: 'success',
						title: '删除成功'
					})
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			/**
			 * 服务完成验证
			 */
			doneServiceValidate() {
				uni.requestSubscribeMessage({
					tmplIds: this.tempIds.butler, // 改成你的小程序订阅消息模板id
					success: (res) => {},
					fail: (res) => {
						console.debug('订阅消息模板错误:' + JSON.stringify(res))
						uni.showToast({
							title: res.errMsg,
							icon: 'error',
							duration: 1000
						})
						if (20001 === res.errCode) {
							console.debug('sub fail no temp return')
						}
					},
				})
				//校验照片信息
				// console.debug('license_photos' + JSON.stringify(this.formData.license_photos))
				// if (!this.formData.license_photos[0]?.url) {
				// 	uni.showToast({
				// 		icon: 'error',
				// 		title: '请上传证件照片'
				// 	})
				// 	return
				// }
				if (!this.formData.license_photos_main.car_license_face ||
					!this.formData.license_photos_main.car_license_back) {
					uni.showToast({
						icon: 'error',
						title: '请上传行驶证正副本'
					})
					return
				}
				if (this.formData.service_photos.length <= 4) {
					uni.showModal({
						content: '未拍满5张工单服务照片，是否完成服务',
						confirmText: '完成服务',
						cancelText: '继续拍照',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								this.doneService()
							} else if (res.cancel) {
								return
							}
						}.bind(this),
						fail: function(err) {
							console.log(err);
						}
					})
				} else {
					return this.doneService()
				}
			},
			doneService() {
				return db.collection(dbCollectionName).doc(this.formDataId).update({
					payment_status: 0,
					status: 3,
					"dates": {
						"service_end": new Date()
					}
				}).then((res) => {
					this.formData.status = 3
					this.updated = false
					uni.showToast({
						icon: 'success',
						title: '服务完成'
					})
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			doneCharge() {
				// 完成收款核算
				return db.collection(dbCollectionName).doc(this.formDataId).update({
					payment_status: 1,
					status: 4,
					"dates": {
						"payment": new Date()
					}
				}).then((res) => {
					uni.showToast({
						icon: 'success',
						title: '收款完成',
						complete() {
							this.autoNavigateBack()
						}
					})
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			async getDetail(id) {
				uni.showLoading({
					title: '加载中···',
					mask: true
				})
				const detailRes = await db.collection(dbCollectionName)
					.where({
						_id: id
					})
					.field(`
					type_id,
					user_id,
					order_sn,
					customer_needs,
					customer_phone,
					customer_location,
					service_content,
					service_add_content,
					store_id,
					offer_price,
					price,
					butler_income,
					butler_id,
					help_butler_id,
					license_photos_main,
					archives_id,
					license_photos,
					service_photos,
					status,
					payment_price,
					payment_order_id,
					score,
					case
					`) // 精准字段控制
					.getTemp()
				db.collection(detailRes, 'yycw_car_service_type', 'yycw_store')
					.get().then((res) => {
						// console.debug(JSON.stringify(res))
						const data = res.result.data[0]
						if (data) {
							db.collection('uni-id-users').doc(data.user_id).field('_id,nickname').get().then((
								res) => {
								this.username = res.result.data[0]?.nickname || '未设置'
							})
							this.formData = data
							if (!this.formData.license_photos) {
								this.formData.license_photos = []
							}
							if (!this.formData.license_photos_main) {
								this.formData.license_photos_main = {}
							}
							if (!this.formData.service_photos) {
								this.formData.service_photos = []
							}
							this.serviceName = data.type_id[0].service_name
							this.storeName = data.store_id[0].store_name
							if (this.formData.status == 1 && this.formData.butler_id === userInfo.uid) {
								//车管家开始服务
								db.collection(dbCollectionName).doc(this.formDataId).update({
									status: 2,
									"dates": {
										"service_start": new Date()
									}
								}).then((res) => {
									this.formData.status = 2
									if (this.formData.status === 2 && (this.role === 'butler' || (this
											.formData.score === 1 && this.role === 'supervisor'))) {
										this.updated = true
									}
								})
							}
							this.orderSn = data.order_sn
							if (this.formData.service_add_content || this.formData.help_butler_id) {
								this.checkedContent = true
							}
							if (this.formData.status === 2 && (this.role === 'butler' || (this.formData.score ===
									1 && this.role === 'supervisor'))) {
								this.updated = true
							}
						} else {
							uni.showToast({
								title: '无服务工单数据',
								icon: 'none'
							})
						}
					})
					.catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						uni.hideLoading()
					})
			},
			makeCall(phone) {
				uni.makePhoneCall({
					phoneNumber: phone
				});
			},
			openNavigation(latitude, longitude, name) {
				if (latitude && longitude) {
					uni.openLocation({
						latitude: latitude,
						longitude: longitude,
						name: name
					})
				} else {
					uni.showToast({
						title: '缺少位置信息'
					})
				}
			},
		}
	}
</script>

<style lang="scss">
	.uni-forms-item {
		padding: 0 15rpx;
	}

	.forms-row {
		margin: 0 15rpx;
		margin-bottom: 20rpx;
	}

	.forms-col {
		margin-right: 15rpx;
	}

	.diy-file-picker {
		width: auto;
	}

	.uni-easyinput__content-textarea {
		font-size: 16rpx;
		min-height: 98rpx !important;
	}

	.is-disabled {
		color: #1e1e1e99 !important;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;

	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 25rpx;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
	}

	.uni-button {
		width: 184px;
		font-size: 30rpx;
	}

	.custom-style {
		color: #ff0000;
		width: 400rpx;
	}
</style>